package com.tdam2014.grupo02;

import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import com.tdam2014.grupo02.R;
import android.app.ListFragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public class MainFragment extends ListFragment {

	private FolderSelectionListener folderSelectionListener;
	private static boolean READ_ASYNC = true;
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
	{
		return inflater.inflate(R.layout.fragment_main, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) 
	{
		super.onActivityCreated(savedInstanceState);
		
		// Para generar folders de prueba //
		//Folder.generateFolders(getActivity());
				
		ArrayList<Folder> list = Folder.getFolders(getActivity());
		if (READ_ASYNC) 
		{
			JsonReader reader = new JsonReader();
			reader.execute();
		}
		
		final FolderAdapter adapter = new FolderAdapter(getActivity());
		if (list != null)
		{
			adapter.setList(list);
		}
		else
		{
			adapter.setList(new ArrayList<Folder>());
		}
		
		setListAdapter(adapter);
		getListView().setOnItemClickListener(new OnItemClickListener() 
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) 
			{
				Folder folder = (Folder) adapter.getItem(position);
				if (folderSelectionListener != null) { folderSelectionListener.onFolderSelected(folder); }
			}
		}
		);
		
	}
	class JsonReader extends AsyncTask<Void, Void, Void> {
		
		public JsonReader() {}
			
		@Override
		protected Void doInBackground(Void... params) 
		{
			try {
				Folder.updateFolder(getActivity());
				// Picture.updateAllPics(getActivity(), Folder.getFolders(getActivity()));
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		
			return null;
		}

		@Override
		protected void onPostExecute(Void result) 
		{
			ArrayList<Folder> list = Folder.getFolders(getActivity());
			final FolderAdapter adapter = new FolderAdapter(getActivity());
			if (list != null)
			{
				adapter.setList(list);
			}
			else
			{
				adapter.setList(new ArrayList<Folder>());
			}
			
			setListAdapter(adapter);
			
		}
	}
	
	public void setFolderSelectionListener(FolderSelectionListener listener) {
		this.folderSelectionListener = listener;
	}
}
